package com.example.qsindusty.jmm_spline.OrdeFragment;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.qsindusty.jmm_spline.Config.Config;
import com.example.qsindusty.jmm_spline.LoginActivity.LoginActivity;
import com.example.qsindusty.jmm_spline.OrderinfoActivity.OrderInfoActivity;
import com.example.qsindusty.jmm_spline.R;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.yixin.ystartlibrary.base.BaseFragment;
import com.yixin.ystartlibrary.base.BaseRecyclerAdapter;
import com.yixin.ystartlibrary.utils.DensityUtil;
import com.yixin.ystartlibrary.utils.GeneralPreferencesUtils;
import com.yixin.ystartlibrary.utils.LoadingDialogUtils;
import com.yixin.ystartlibrary.utils.LogUtils;
import com.yixin.ystartlibrary.utils.ToastUtils;
import com.yixin.ystartlibrary.utils.Utils;
import com.yixin.ystartlibrary.widget.DiverItemDecoration;
import com.yixin.ystartlibrary.widget.EmptyRecyclerView;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;


public class OrderCompelteFragment extends BaseFragment implements OrderCotract.View {
    public static boolean isFresh = false;
    @BindView(R.id.materialHeader)
    MaterialHeader materialHeader;
    @BindView(R.id.recyclerview)
    EmptyRecyclerView recyclerview;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    Unbinder unbinder;
    OrderCotract.Persenter mPresenter;
    OrderAdapter orderAdapter;
    /*  未分配司机， 已分配司机，  未接货，   运输中， 已完成 0-4*/
    String row = Config.row;//默认为10条
    String page = Config.page;//默认第一页
    String status = Config.status_order_COMPELETD;//默认为2未接货
    @BindView(R.id.iv_empty)
    ImageView ivEmpty;
    @BindView(R.id.empty_text)
    TextView emptyText;

    public OrderCompelteFragment() {
        // Required empty public constructor
    }


    public static OrderCompelteFragment newInstance() {
        OrderCompelteFragment fragment = new OrderCompelteFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_order, container, false);
        unbinder = ButterKnife.bind(this, view);

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isFresh) {
            page="1";
            getOrder();
            isFresh = false;
        }
    }


    @Override
    protected int getContextView() {
        return 0;
    }

    @Override
    protected void init() {
        bindPresenter();
        initrefresh();
        getOrder();
        initview();
    }

    @Override
    protected void initBundleData() {

    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        unbindPresenter();
    }

    private void initrefresh() {
        refreshLayout.setEnableScrollContentWhenLoaded(false);
        refreshLayout.setEnableAutoLoadmore(false);
        refreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                mPresenter.getOrder(GeneralPreferencesUtils.getSharedPreference(getActivity(), "token", null), status, row, page);
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = "1";
                LogUtils.e("page==" + page);
                mPresenter.getOrder(GeneralPreferencesUtils.getSharedPreference(getActivity(), "token", null), status, row, page);

            }
        });
    }


    private void initview() {
        orderAdapter = new OrderAdapter();
        recyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
        DiverItemDecoration itemDecoration = new DiverItemDecoration(DiverItemDecoration.VERTICAL);
        itemDecoration.setSize(DensityUtil.dip2px(getActivity(), 0.5f));
        itemDecoration.setColor(ContextCompat.getColor(getActivity(), R.color.default_layout_color));
        recyclerview.addItemDecoration(itemDecoration);
        //解决ScrollView嵌套RecyclerView滑动卡帧
        recyclerview.setNestedScrollingEnabled(false);
        recyclerview.setAdapter(orderAdapter);
        emptyText.setText("试试下拉刷新");
        recyclerview.setEmptyView(LayoutInflater.from(getActivity()).inflate(R.layout.item_emptyview, null));

    }

    AlertDialog alertDialog;

    @Override
    public void showLoading() {
        alertDialog = LoadingDialogUtils.create(getActivity(), "");
        alertDialog.show();

    }

    @Override
    public void closeLoading() {
        if (alertDialog != null && alertDialog.isShowing())
            alertDialog.dismiss();
    }

    @Override
    public void bindPresenter() {
        if (mPresenter == null) {
            mPresenter = new OrderPresenter();
        }
        mPresenter.bindView(this);
    }

    @Override
    public void unbindPresenter() {
        mPresenter.unbindView();
    }

    @Override
    public void getOrder() {
        mPresenter.getOrder(GeneralPreferencesUtils.getSharedPreference(getActivity(), "token", null), status, row, page);

    }

    @Override
    public void refresshDataSuccessful(OrderData data) {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadmore();
        if (page.equals("1")) {
            orderAdapter.clearInfoList();
            orderAdapter.addInfoList(data.getData());
        } else {
            orderAdapter.addInfoList(data.getData());
        }
        int p = Integer.parseInt(page);
        page = String.valueOf(p + 1);
        orderAdapter.notifyDataSetChanged();
    }

    @Override
    public void refreshNoMore(String msg) {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadmore();

        if (TextUtils.equals(page, "1")) {
            orderAdapter.clearInfoList();
        } else {

        }
        ToastUtils.showLongToast(getActivity(), msg);
        orderAdapter.notifyDataSetChanged();
    }

    @Override
    public void refreshDataFraier(String msg) {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadmore();
        ToastUtils.showLongToast(getActivity(), msg);
    }

    @Override
    public void nologin() {
        Utils.startIntent(getActivity(), LoginActivity.class);
    }

    @Override
    public void markSuccessful(String msg, String status, int position) {

    }

    @Override
    public void markFairer(String msg) {

    }

    @OnClick(R.id.iv_empty)
    public void onIvEmptyClicked() {
    }

    @OnClick(R.id.empty_text)
    public void onEmptyTextClicked() {
    }


    public class OrderAdapter extends BaseRecyclerAdapter<OrderData.DataBean, OrderAdapter.ViewHolder> {
        @Override
        protected void onBindViewHolder(int position, ViewHolder holder) {
            OrderData.DataBean dataBean = getItem(position);
            holder.setvauels(dataBean);
        }

        @Override
        protected ViewHolder getViewHolder(ViewGroup parent, int viewType) {
            return new ViewHolder(inflate(R.layout.item_order, parent));

        }

        @Override
        protected void onBindItemClickListener(View v, int position) {
            super.onBindItemClickListener(v, position);
            Intent intent = new Intent(getActivity(), OrderInfoActivity.class);
            intent.putExtra("flag","0");
            intent.putExtra("data", getItem(position));
            startActivity(intent);
        }
        class ViewHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.company)
            TextView company;
            @BindView(R.id.driver_bottom)
            TextView driverBottom;
            @BindView(R.id.order_status)
            TextView orderStatus;
            @BindView(R.id.ordernum)
            TextView ordernum;
            @BindView(R.id.startaddress)
            TextView startaddress;
            @BindView(R.id.endaddress)
            TextView endaddress;
            @BindView(R.id.goodstime)
            TextView goodstime;
            @BindView(R.id.fahuotimelin)
            LinearLayout fahuotimelin;
            @BindView(R.id.requiretimelin)
            LinearLayout requiretimelin;
            @BindView(R.id.requiretime)
            TextView requiretime;
            @BindView(R.id.goods)
            TextView goods;
            @BindView(R.id.jiehuotime)
            TextView jiehuotime;
            @BindView(R.id.jiehuolin)
            LinearLayout jiehuolin;
            @BindView(R.id.ordertime)
            TextView ordertime;
            @BindView(R.id.ordertimelin)
            LinearLayout ordertimelin;
            @BindView(R.id.carnum)
            TextView carnum;
            @BindView(R.id.carlin)
            LinearLayout carlin;
            @BindView(R.id.drviername)
            TextView drviername;
            @BindView(R.id.drivierlin)
            LinearLayout drivierlin;

            ViewHolder(View view) {
                super(view);
                ButterKnife.bind(this, view);
            }

            void setvauels(OrderData.DataBean dataBean) {
                requiretimelin.setVisibility(View.VISIBLE);
                jiehuolin.setVisibility(View.GONE);
                ordertimelin.setVisibility(View.VISIBLE);
                driverBottom.setVisibility(View.GONE);
                carlin.setVisibility(View.GONE);
                drivierlin.setVisibility(View.GONE);
                if (!TextUtils.isEmpty(dataBean.getQYMC()))
                    company.setText(dataBean.getQYMC());
                if (!TextUtils.isEmpty(dataBean.getFJRDZ()))
                    startaddress.setText(dataBean.getFJRDZ());
                if (!TextUtils.isEmpty(dataBean.getSJRDZ()))
                    endaddress.setText(dataBean.getSJRDZ());
                if (!dataBean.getGOODSLIST().isEmpty()) {
                    StringBuilder goodsName = new StringBuilder();
                    for (OrderData.DataBean.GOODSLISTBean goodslistBean : dataBean.getGOODSLIST()) {
                        goodsName = goodsName.append(goodslistBean.getMC()).append("|").append(goodslistBean.getSL() + goodslistBean.getDW()).append("  ");
                    }
                    goods.setText(goodsName);

                }
                if (!TextUtils.isEmpty(dataBean.getDH()))
                    ordernum.setText(dataBean.getDH());
                if (!TextUtils.isEmpty(dataBean.getFHSJ()))
                    requiretime.setText(dataBean.getFHSJ());
                if (!TextUtils.isEmpty(dataBean.getCJSJ()))
                    ordertime.setText(dataBean.getCJSJ());

                if (!TextUtils.isEmpty(dataBean.getGLXH())) {
                    driverBottom.setText(dataBean.getGLXH());
                    driverBottom.setText("组合订单");
                    driverBottom.setTextColor(getResources().getColor(R.color.white));
                    driverBottom.setBackgroundColor(getResources().getColor(R.color.theme_color));
                    driverBottom.setEnabled(false);
                } else {
                    driverBottom.setVisibility(View.GONE);
                    driverBottom.setText("选择司机");
                    driverBottom.setEnabled(true);
                }


            }

        }

    }

}
